<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/3.0.0-beta.1/jsencrypt.js"></script>
    <script src="http://cdn.bootcss.com/crypto-js/3.1.9/crypto-js.js"></script>
    <script src="./js/encrypt.js"></script>
    <title>RSA+AES</title>
</head>

<body>
    <div id="app">
        <div style="text-align: center">hello world</div>
        <div class="input-wrapper">
            <el-input v-model="userName" placeholder="请输入用户名"></el-input>
        </div>
        <div class="input-wrapper">
            <el-input v-model="userPwd" type="password" placeholder="请输入密码"></el-input>
        </div>
        <div class="input-wrapper">
            <el-button type="primary" size="medium" v-on:click="sendLogin">登录</el-button>
        </div>
    </div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            userName: '',
            userPwd: ''
        },
        mounted: function () {
            //创建随机数做为秘钥[可以使用uuid]
            var date = new Date();
            date = date.getTime() + '000';  //iv 固定为16位，   使用128的话秘钥16位，256则32位 
            localStorage.setItem('encryptKey', date); //将随机秘钥放入本地
        },
        methods: {
            sendLogin: function () {
                if (this.userName.trim() == '') {
                    this.$message({
                        message: '用户名不为空',
                        type: 'warning'
                    });
                    return false;
                }
                if (this.userPwd.trim() == '') {
                    this.$message({
                        message: '密码不为空',
                        type: 'warning'
                    });
                    return false;
                }
                axios.post('http://localhost/login.php', {
                    userName: this.userName,
                    userPwd: this.userPwd
                }).then(res => {
                    var res = res.data;
                    if (res.respCode == '00') {
                        localStorage.setItem('user_token', res.data.user_token)
                        this.$message({
                            message: '登录成功',
                            center: true
                        });
                    } else {
                        this.$message({
                            message: res.respMsg,
                            type: 'warning'
                        });
                    }
                }).catch(err => {

                });
            }
        }
    })

    // 请求拦截器
    // 在发送请求之前做些什么
    axios.interceptors.request.use(function (config) {
        //判断用户数据是否需要加密
        var arr = Object.keys(config.data);
        var len = arr.length;
        var user_token = localStorage.getItem('user_token');
        if (len > 0 || user_token !== null) {
            //node环境可以使用Qs格式化
            var ret = '';
            for (let it in config.data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(config.data[it]) + '&';
            }
            var encrypt = new Encrypt(); //实例化
            var encryptKey = localStorage.getItem('encryptKey'); //随机秘钥
            var encryptStr = encrypt.AesEncrypt(ret, encryptKey); //对用户提交数据加密
            if (user_token === null) {
                //TODO:: 如果用户不存在token，表示用户未登陆成功，需要传递随机秘钥给后端
                //将随机秘钥进行RSA加密传递给后端
                encryptKey = encrypt.RsaEncrypt(encryptKey);
                sendData = 'content=' + encryptStr + '&encryptKey=' + encryptKey;
            } else {
                //token已存在则使用RSA加密传递给后台
                var encryptToken = encrypt.RsaEncrypt(user_token);
                sendData = 'content=' + encryptStr + '&encryptToken=' + encryptToken;
            }
            config.data = sendData;
        }
        return config;
    }, function (error) {
        // 对请求错误做些什么
        console.log(error);
    });



    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
        // 对数据解密
        var data = response.data.data.content
        if (data != undefined) {
            //需要解密
            var encrypt = new Encrypt(); //实例化
            var res = encrypt.AesDecrypt(data, localStorage.getItem('encryptKey'));
            response.data.data = JSON.parse(res);
            return response;
        }
        return response;
    }, function (error) {
        // 对响应错误做点什么
        return Promise.reject(error);
    });



</script>

<style>
    .input-wrapper {
        margin-top: 15px
    }
</style>

</html>